package com.nfl.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;

public class PhoneInfo {
	private static final String FILE_MEMORY = "/proc/meminfo";
	private static final String FILE_CPU = "/proc/cpuinfo";

	// 判断手机是否联网
	public static boolean isConnectInternet(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		if (info != null && info.isAvailable()) {
			return true;
		}
		return false;
	}

	/**
	 * @Title: connNetType
	 * @Description: TODO
	 * @param @param context
	 * @param @return
	 * @return 判断用户网络链接类型 -1：没有网络 1：WIFI网络2：wap网络3：net网络
	 * @throws
	 */
	public static int connNetType(Context context) {
		int netType = -1;
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
				netType = 3;
			} else {
				netType = 2;
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = 1;
		}
		return netType;
	}

	/**
	 * @Title: isAvilible
	 * @Description: 断手机已安装某程序
	 * @param @param context
	 * @param @param packageName
	 * @param @return
	 * @return boolean
	 * @throws
	 */
	public static boolean isAviliblePackage(Context context, String packageName) {
		final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
		List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
		// 从pinfo中将包名字逐一取出，压入pName list中
		if (pinfo != null) {
			for (int i = 0; i < pinfo.size(); i++) {
				String pn = pinfo.get(i).packageName;
				pName.add(pn);
			}
		}
		return pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
	}

	// 获取SD卡的大小
	@SuppressWarnings("deprecation")
	public static String getSDCard() {
		long blocSize = 0;
		long availableBlocks = 0;
		// 首先判断SD卡是否已经插好
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File path = Environment.getExternalStorageDirectory();
			StatFs statfs = new StatFs(path.getPath());
			blocSize = statfs.getBlockSize();
			availableBlocks = statfs.getBlockCount();
			return "" + (blocSize * availableBlocks);
		}
		return "0";
	}

	// 获取手机的MAC地址
	public static String getMacAddress(Context context) {
		String result = "";
		WifiManager wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		result = wifiInfo.getMacAddress();
		return result;
	}

	// 获取SDK release
	public static String getSDKRelease() {
		return Build.VERSION.RELEASE;
	}

	// 获取空闲内存(MB)
	public static long getFreeMem(Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Activity.ACTIVITY_SERVICE);
		MemoryInfo info = new MemoryInfo();
		am.getMemoryInfo(info);
		long free = info.availMem / 1024 / 1024;
		return free;
	}

	// 获取总内存(MB)
	public static String getTotalMem(Context context) {
		try {
			FileReader fr = new FileReader(FILE_MEMORY);
			BufferedReader br = new BufferedReader(fr);
			String text = br.readLine();
			String[] array = text.split("\\s+");
			br.close();
			return "" + Long.valueOf(array[1]) / 1024;
		} catch (Exception e) {
			//
			return "" + (-1);
		}
	}

	// 获取CPU信息
	public static String getCpuInfo() {
		String str = "";
		String[] cpu = { "", "" }; // 1-cpu型号 //2-cpu频率
		String cpuInfo = "";
		String[] arrayOfString;
		try {
			FileReader fr = new FileReader(FILE_CPU);
			BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
			str = localBufferedReader.readLine();
			arrayOfString = str.split("\\s+");
			for (int i = 2; i < arrayOfString.length; i++) {
				cpu[0] = cpu[0] + arrayOfString[i] + " ";
			}
			str = localBufferedReader.readLine();
			arrayOfString = str.split("\\s+");
			cpu[1] += arrayOfString[2];
			localBufferedReader.close();
			cpuInfo = cpu[0] + "-" + cpu[1];
		} catch (IOException e) {
			//
		}
		return cpuInfo;
	}

	/**
	 * 获取系统SDK版本
	 * 
	 * @return
	 */
	public static int getSDKVersionNumber() {
		int sdkVersion;
		try {
			sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
		} catch (NumberFormatException e) {
			sdkVersion = 0;
		}
		return sdkVersion;
	}

	/**
	 * 
	 * @desc 获取应用版本信息
	 * @param @param ctx
	 * @param @return
	 * @return String
	 */
	public static String getAppVersionName(Context ctx) {
		String version = "";
		PackageManager manager = ctx.getPackageManager();
		PackageInfo info;
		try {
			info = manager.getPackageInfo(ctx.getPackageName(), 0);
			version = info.versionName;
		} catch (NameNotFoundException e) {
			Log.d("context", e.getMessage()) ;
		}

		return version;
	}

	/**
	 * 获得屏幕的高宽 int[] 2015年10月12日
	 * 
	 * @param context
	 * @return
	 */
	public static int[] getScreenSize(Context context) {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(displayMetrics);
		int screen[] = { displayMetrics.widthPixels,
				displayMetrics.heightPixels };
		// 天语 // 华为
		// displayMetrics.density // 1.5 // 2.0 // 屏幕密度
		// displayMetrics.densityDpi // 240 // 320 // 屏幕dpi
		// displayMetrics.heightPixels // 800 // 1280 // 屏幕高度
		// displayMetrics.scaledDensity // 1.5 // 2.0 // 用于字体，与屏幕密度一致，可更改
		// displayMetrics.widthPixels // 480 // 720 // 屏幕宽度
		// displayMetrics.xdpi // 160.42105 // 332.5091 // The exact physical
		// pixels per inch of the screen in the X dimension.
		// displayMetrics.ydpi // 159.49706 // 331.7551 // The exact physical
		// pixels per inch of the screen in the Y dimension.
		// displayMetrics.DENSITY_LOW = 120dpi
		// displayMetrics.DENSITY_MEDIUM = 160dpi
		// displayMetrics.DENSITY_HIGH = 240dpi
		// displayMetrics.DENSITY_XHIGH = 320dpi
		// displayMetrics.DENSITY_XXHIGH = 480dpi
		// displayMetrics.DENSITY_XXXHIGH = 640dpi
		// displayMetrics.DENSITY_TV = 213dpi
		// displayMetrics.DENSITY_400 = 400dpi
		return screen;
	}

	/**
	 * 获取IMEI号，IESI号，手机型号
	 */
	public static void getInfo(Context context) {
		TelephonyManager mTm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = mTm.getDeviceId();// 获取手机的IMEI码(国际移动用户识别码)
		// 由于厂商修改了TelephonyManager的?getDeviceID方法，导致无法使用getDeviceID方法获取IMEI号码。
		if (null == imei) {
			imei = "000000000000000";
		}
		String imsi = mTm.getSubscriberId();
		String mtype = android.os.Build.MODEL; // 手机型号
		String mtyb = android.os.Build.BRAND;// 手机品牌
		String numer = mTm.getLine1Number(); // 手机号码，有的可得，有的不可得
		Log.i("text", "手机IMEI号：" + imei + "手机IESI号：" + imsi + "手机型号：" + mtype
				+ "手机品牌：" + mtyb + "手机号码" + numer);
	}

	/**
	 * 得到手机品牌
	 * 
	 * @return
	 */
	public static String getPhoneBrand() {
		return android.os.Build.BOARD;
	}

	/**
	 * 获得状态栏的高度 ；方法一：
	 */
	public static int getStatusBarHeight(Context context) {
		int status_bar_height = 0;
		int resourceId = context.getResources().getIdentifier(
				"status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			status_bar_height = context.getResources().getDimensionPixelSize(
					resourceId);
		}
		return status_bar_height;
	}

	/**
	 * 获得状态栏的高度 ；方法二：
	 */
	public static int getStatusHeight(Context context) {

		int statusHeight = -1;
		try {
			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height")
					.get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e) {
			Log.d("context", e.getMessage()) ;
		}
		return statusHeight;
	}

	/**
	 * 获得状态栏的高度 ；方法三： 不推荐使用，因为这个方法依赖于WMS(窗口管理服务的回调)。
	 */
	public static int getStatusBarHeightTest(Context context) {
		Rect rectangle = new Rect();
		Window window = ((Activity) context).getWindow();
		window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
		int statusBarHeight = rectangle.top;
		return statusBarHeight;
	}

}
